import os
import subprocess
import datetime
import conf

__all__ = ["runtest"]

def run(command, get_ret = True, get_err = True, filter_warnings = False):
  """
  Execute the given command and return a tuple consisting of
  (returncode, stdout, stderr).

  The stdout is always returned, but the other return values
  can be skipped for efficiency if not required.

  If get_ret param is False, don't wait for return code, just
  return 0.

  If get_err param is False, don't get the stderr, just return "".

  If filter_warnings param is True, remove Wanring and Error lines
  from output.

  Note: previous versions of this code have hung due to buffering
  problems where the command produced long output (> 20k) and
  where stderr was read before stdout.
  """
  debug(command)

  proc = subprocess.Popen(command, \
                          shell = True, \
                          stdout = subprocess.PIPE, \
                          stderr = subprocess.PIPE)

  output = proc.stdout.read()

  if filter_warnings:
    output = remove_warnings(output)
    output = remove_blanks(output)

  error = ""
  if get_err:
    error = proc.stderr.read()

  returncode = 0
  if get_ret:
    returncode = proc.wait()
  return [returncode, output, error]

def auth(username, passwd):
    command = "ssh %s@%s \"%s '%s' '%s'\"" % \
               (conf.AUTH_AGENT_SSH_USER,
                conf.TESTOPIA_SERVER,
                conf.AUTH_AGENT,
                username, 
                passwd)
    return run(command)

def sendemail(to, cc, fr, subject, body):

    mail_content = \
"""
To: %s
Cc: %s
From: %s
Subject: %s

%s
""" % (to, cc, fr, subject, body)

    proc = subprocess.Popen("/usr/bin/mailx -t", \
                            shell = True, \
                            stdout = subprocess.PIPE, \
                            stderr = subprocess.PIPE)

def addclient(os_rel, build_no, hostname, domain, mac, arch, ai_manifest, sc_profile):
    arch_alias = {
        'sparc': 'sun4v',
        'x86': 'i386',
    }

    command = "%s -o -b %s -m %s -P %s -e %s %s.%s %s %s" % \
               (conf.ADDCLIENT_CMD, 
                build_no, 
                ai_manifest, 
                sc_profile, 
                mac, 
                hostname,
                domain,
                os_rel, 
                arch_alias[arch.lower()])

    return run(command)

def delclient(hostname, domain):
    command = 'echo "%s -d %s.%s" | at now + 30 minutes' % \
               (conf.DELCLIENT_CMD, 
                hostname,
                domain)

    return run(command)


def reboot(hostname, domain):
    command = 'ssh %s@%s.%s "nohup %s neti >> /var/tmp/csc.log 2>&1 &"' \
                % (conf.SSH_USER, hostname, domain, conf.CSC_CMD)
    return run(command)

def osu(hostname, domain):
    command = 'ssh %s@%s.%s "nohup %s osu >> /var/tmp/csc.log 2>&1 &"' \
                % (conf.SSH_USER, hostname, domain, conf.CSC_CMD)
    return run(command)


def dtu(hostname, domain, build_no='latest'):
    command = 'ssh %s@%s.%s "nohup %s dti %s >> /var/tmp/csc.log 2>&1 &"' \
                % (conf.SSH_USER, hostname, domain, conf.CSC_CMD, build_no)
    return run(command)

def runtest(hostname, domain, task_id, testrun_name, dryrun = True):
    #command = "ssh %s@%s.%s \"echo \\\"/opt/wox/framework/wox %s -t %s %s\\\" | at now\"" \
    command = 'ssh %s@%s.%s "nohup %s %s -i %s %s >> /var/tmp/wox.log 2>&1 &"' \
                % (conf.SSH_USER, 
                   hostname, 
                   domain, 
                   conf.WOX_CMD, 
                   ('-n' if dryrun else ''), 
                   task_id,
                   testrun_name)
    return run(command)


def grablog(hostname, domain, log_token):
    log_prefix = "/var/tmp/wox.log"
    command = "ping %s.%s >/dev/null 2>&1 && ssh %s@%s.%s \"cat %s.%s\" 2>/dev/null" \
                 % (hostname,
                    domain,
                    conf.SSH_USER, 
                    hostname,
                    domain,
                    log_prefix,
                    log_token)
    return run(command)

def getbldlst(hostname, domain, os_rel):
    command = "%s -b FOO_BUILD %s.%s %s i86pc" % (conf.ADDCLIENT_CMD, hostname, domain, os_rel)
    return run(command)


def getent(hostname, domain):
    return run("getent hosts %s.%s 2>/dev/null" % (hostname, domain))


def cron_jobs(at_time, jids):
    command = "echo '%s at %s' | at %s" % \
                (conf.BG_TRIGGER , 
                 conf.URL_VS.join(map(str, jids)),
                 at_time)
    return run(command)

import logging
def debug(msg):
    logging.info("\n++++++++ DEBUG ++++++++\n%s\n+++++++++++++++++++++++\n" % msg)

